import React, { useState, useRef, useEffect } from 'react';
import { Modal, InputItem } from 'antd-mobile-v2';
import styles from './index.module.less';
import { useSelector } from 'react-redux';
import classnames from 'classnames';

interface Props {
  visible?: boolean;
  closable?: boolean;
  popup?: boolean;
  title?: string;
  maxLength?: number;
  phone?: string;
  sendVerificationCode: any;
  checkVerificationCode: any;
  handleSuccess: any;
  handleModalClose?: () => void;
}

const VerificationCodeModal: React.FC<Props> = (props) => {
  const { userInfo } = useSelector((state: any) => {
    return {
      userInfo: state.common.userInfo
    };
  });

  const {
    visible = false,
    closable = true,
    popup = true,
    title,
    handleModalClose,
    maxLength = 4,
    phone = userInfo?.mobile,
    sendVerificationCode,
    checkVerificationCode,
    handleSuccess
  } = props;

  const [code, setCode] = useState<string>(''); // 存储input值
  const [codeList, setCodeList] = useState<string[]>([]); // input值分割后的数组
  const [codeContent] = useState<string[]>(new Array(maxLength).fill(''));
  const [delay, setDelay] = useState<number>(60);
  const [disable, setDisable] = useState<boolean>(false); // 控制是否可以输入验证码

  const inputRef = useRef<any>();

  useEffect(() => {
    setCodeList(code.split(''));
    triggerCheck();
  }, [code]);

  useEffect(() => {
    startCount();
  }, [delay, visible]);

  useEffect(() => {
    if (!visible) return;
    inputRef.current?.focus();
  }, [visible]);

  const handleClose = () => {
    setCode('');
    setDelay(60);
    setDisable(false);
    handleModalClose && handleModalClose();
  };

  const startCount = async () => {
    if (delay === 0) return;
    if (delay === 60 && !visible) return;
    if (delay === 60 && visible) {
      sendVerificationCode();
    }
    setTimeout(() => {
      setDelay(delay - 1);
    }, 1000);
  };

  const handleCodeChange = (val) => {
    setCode(val);
  };

  const handleCodeClick = () => {
    inputRef.current?.focus();
  };

  const triggerCheck = async () => {
    if (code.length < maxLength) return;
    setDisable(true);
    checkVerificationCode(code)
      .then((res) => {
        if (res.status === 200) {
          handleSuccess();
          setCode('');
          setDelay(60);
        }
      })
      .finally(() => {
        setDisable(false);
      });
  };

  const handleRestartVerifi = () => {
    setCode('');
    setDelay(60);
  };

  return (
    <Modal
      visible={visible}
      closable={closable}
      popup={popup}
      title={title}
      onClose={handleClose}
      className={styles.modal}
      wrapClassName={styles.modalWrap}
    >
      <div className={styles.content}>
        <p className={styles.text}>
          涉及电子签章等敏感操作，请输入短信验证码进行身份验证，验证码已发送至
          {phone}。
        </p>
        <div className={styles.contentMain}>
          <div className={styles.inputWrap}>
            <InputItem
              ref={inputRef}
              type={'number'}
              maxLength={maxLength}
              value={code}
              onChange={handleCodeChange}
              disabled={disable}
            >
            </InputItem>
          </div>
          <div className={styles.codeContent} onClick={handleCodeClick}>
            {codeContent.map((_item: string, index: number) => (
              <div className={styles.codeItem} key={index}>
                {codeList[index]}
              </div>
            ))}
          </div>
        </div>
        {delay === 0 ? (
          <div className={styles.restart} onClick={handleRestartVerifi}>
            重新发送
          </div>
        ) : (
          <div className={classnames(styles.restart, styles.delay)}>
            {delay}秒后重新发送
          </div>
        )}
      </div>
    </Modal>
  );
};

export default VerificationCodeModal;
